<template>
  <view class="container" :class="{ dark: isDark }">
    <!-- 连接控制栏 -->
    <view class="connection-bar">
      <input
        class="ip-input"
        type="text"
        v-model="ip"
        placeholder="请输入树莓派IP地址"
        :disabled="isConnected"
      />
      <button
        class="connect-btn"
        @click="toggleConnection"
        :type="isConnected ? 'warn' : 'primary'"
        :loading="connecting"
      >
        {{ isConnected ? "断开连接" : connecting ? "连接中..." : "连接" }}
      </button>
    </view>

    <!-- 连接状态指示器 -->
    <view class="status-indicator">
      连接状态:
      <text :style="{ color: isConnected ? '#4CAF50' : '#F44336' }">
        {{ connectionStatusText }}
      </text>
      <text v-if="connectionError" class="error-text">{{ connectionError }}</text>
    </view>

    <!-- 视频显示区域 -->
    <view class="video-container">
      <web-view 
        v-if="videoUrlForWebView" 
        :src="videoUrlForWebView" 
        @message="handleVideoMessage"
      />
      <view v-else class="video-placeholder">
        <image src="/static/images/video-offline.png" class="placeholder-image" />
        <text class="placeholder-text">{{ videoStatusText }}</text>
      </view>
    </view>

    <!-- 控制面板 -->
    <view class="control-panels">
      <!-- 移动控制面板 -->
      <view class="panel">
        <text class="panel-title">移动控制 (按住移动)</text>
        <view class="d-pad">
          <view class="d-pad-center">
            <button 
              class="stop-btn" 
              @click="sendCommand('stop')"
              :disabled="!isConnected"
            >
              停止
            </button>
          </view>
          <button
            class="d-pad-btn up"
            @touchstart="handleMoveStart('forward')"
            @touchend="handleMoveStop"
            :disabled="!isConnected"
            >↑</button
          >
          <button
            class="d-pad-btn left"
            @touchstart="handleMoveStart('left')"
            @touchend="handleMoveStop"
            :disabled="!isConnected"
            >←</button
          >
          <button
            class="d-pad-btn right"
            @touchstart="handleMoveStart('right')"
            @touchend="handleMoveStop"
            :disabled="!isConnected"
            >→</button
          >
          <button
            class="d-pad-btn down"
            @touchstart="handleMoveStart('backward')"
            @touchend="handleMoveStop"
            :disabled="!isConnected"
            >↓</button
          >
        </view>
      </view>

      <!-- 云台控制面板 -->
      <view class="panel">
        <text class="panel-title">云台控制</text>
        <view class="d-pad">
          <view class="d-pad-center">
            <button 
              class="center-btn" 
              @click="sendCommand('servo_center')"
              :disabled="!isConnected"
            >
              归中
            </button>
          </view>
          <button 
            class="d-pad-btn up" 
            @click="sendCommand('servo_up')"
            :disabled="!isConnected"
          >↑</button>
          <button
            class="d-pad-btn left"
            @click="sendCommand('servo_left')"
            :disabled="!isConnected"
            >←</button
          >
          <button
            class="d-pad-btn right"
            @click="sendCommand('servo_right')"
            :disabled="!isConnected"
            >→</button
          >
          <button 
            class="d-pad-btn down" 
            @click="sendCommand('servo_down')"
            :disabled="!isConnected"
          >↓</button>
        </view>
      </view>
    </view>

    <!-- 功能按钮 -->
    <view class="function-buttons">
      <button 
        @click="sendCommand('sing')"
        :disabled="!isConnected"
      >
        🎵 切换音乐
      </button>
      <button 
        type="primary" 
        @click="sendCommand('start_avoid')"
        :disabled="!isConnected || robotStatus.avoid_mode"
      >
        🤖 开启避障
      </button>
      <button 
        type="warn" 
        @click="sendCommand('stop_avoid')"
        :disabled="!isConnected || !robotStatus.avoid_mode"
      >
        🚫 关闭避障
      </button>
    </view>

    <!-- 状态显示 -->
    <view class="status-box">
      <text class="panel-title">机器人状态</text>
      <view class="status-item">
        <text>避障模式:</text>
        <text :class="['status-value', robotStatus.avoid_mode ? 'active' : '']">{{
          robotStatus.avoid_mode ? "开启" : "关闭"
        }}</text>
      </view>
      <view class="status-item">
        <text>音乐播放:</text>
        <text :class="['status-value', robotStatus.singing ? 'active' : '']">{{
          robotStatus.singing ? "开启" : "关闭"
        }}</text>
      </view>
      <view class="status-item">
        <text>烟雾检测:</text>
        <text
          :class="['status-value', robotStatus.sensors.smoke ? 'danger' : '']"
          >{{ robotStatus.sensors.smoke ? "检测到烟雾!" : "正常" }}</text
        >
      </view>
      <view class="status-item">
        <text>左侧障碍:</text>
        <text class="status-value">{{
          robotStatus.sensors.left ? "无" : "有"
        }}</text>
      </view>
      <view class="status-item">
        <text>右侧障碍:</text>
        <text class="status-value">{{
          robotStatus.sensors.right ? "无" : "有"
        }}</text>
      </view>
      <view class="status-item">
        <text>电池电量:</text>
        <text class="status-value">{{ batteryLevel }}%</text>
        <progress 
          :percent="batteryLevel" 
          stroke-width="10" 
          :activeColor="batteryColor"
          backgroundColor="#eee"
        />
      </view>
    </view>
    
    <!-- 连接状态Toast -->
    <uni-popup ref="connectionToast" type="message">
      <uni-popup-message 
        :type="toastType" 
        :message="toastMessage" 
        :duration="2000"
      />
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      ip: "",                      // 树莓派IP地址
      isConnected: false,          // 是否已连接
      connecting: false,           // 是否正在连接中
      connectionError: "",         // 连接错误信息
      socketTask: null,            // WebSocket连接对象
      videoUrlForWebView: "",      // 视频流URL
      statusInterval: null,        // 状态轮询定时器
      moveInterval: null,          // 持续移动定时器
      currentDirection: "",        // 当前移动方向
      isDark: false,               // 暗黑模式
      batteryLevel: 0,             // 电池电量
      toastType: "success",        // Toast类型
      toastMessage: "",            // Toast消息
      
      // 机器人状态
      robotStatus: {
        avoid_mode: false,         // 避障模式状态
        singing: false,            // 音乐播放状态
        sensors: { 
          smoke: false,            // 烟雾传感器
          left: 1,                // 左侧障碍物传感器 (1表示无障碍)
          right: 1                 // 右侧障碍物传感器
        },
      },
    };
  },
  
  computed: {
    // 连接状态文本
    connectionStatusText() {
      return this.isConnected ? "已连接" : this.connecting ? "连接中..." : "已断开";
    },
    
    // 视频状态文本
    videoStatusText() {
      if (!this.isConnected) return "请先连接机器人";
      if (this.connecting) return "正在连接视频流...";
      return "视频流未连接";
    },
    
    // 电池颜色
    batteryColor() {
      if (this.batteryLevel > 60) return "#4CAF50";
      if (this.batteryLevel > 20) return "#FFC107";
      return "#F44336";
    }
  },
  
  onShow() {
    // 检查暗黑模式设置
    this.checkDarkMode();
    
    // 从本地存储加载上次连接的IP
    const lastIp = uni.getStorageSync("robot_ip");
    if (lastIp) {
      this.ip = lastIp;
    }
  },
  
  onUnload() {
    // 页面卸载时断开连接
    this.disconnect();
  },
  
  methods: {
    // 检查暗黑模式设置
    checkDarkMode() {
      const dark = getApp().globalData.darkMode;
      this.isDark = dark;
      
      // 设置导航栏和tabbar样式
      if (dark) {
        uni.setTabBarStyle({
          backgroundColor: '#1e1e1e',
          borderStyle: 'black',
          color: '#999999',
          selectedColor: '#ffffff'
        });
        uni.setNavigationBarColor({
          frontColor: '#ffffff',
          backgroundColor: '#1e1e1e'
        });
      } else {
        uni.setTabBarStyle({
          backgroundColor: '#ffffff',
          borderStyle: 'black',
          color: '#7A7E83',
          selectedColor: '#fb7e29'
        });
        uni.setNavigationBarColor({
          frontColor: '#000000',
          backgroundColor: '#F8F8F8'
        });
      }
    },
    
    // 显示Toast消息
    showToast(type, message) {
      this.toastType = type;
      this.toastMessage = message;
      this.$refs.connectionToast.open();
    },
    
    // 切换连接状态
    toggleConnection() {
      if (this.isConnected) {
        this.disconnect();
      } else {
        this.connect();
      }
    },
    
    // 连接到机器人
    connect() {
      if (!this.ip) {
        this.showToast("error", "请输入IP地址");
        return;
      }
      
      if (this.socketTask) {
        this.showToast("warning", "已经连接或连接中");
        return;
      }

      const wsUrl = `ws://${this.ip}:8765`;
      this.connecting = true;
      this.connectionError = "";
      uni.showLoading({ title: "连接中..." });

      // 创建WebSocket连接
      this.socketTask = uni.connectSocket({ 
        url: wsUrl,
        success: () => {
          console.log("WebSocket连接请求已发送");
        },
        fail: (err) => {
          console.error("WebSocket连接失败:", err);
          this.connecting = false;
          this.showToast("error", "连接失败");
        }
      });

      // 连接成功回调
      this.socketTask.onOpen(() => {
        uni.hideLoading();
        this.showToast("success", "连接成功");
        this.isConnected = true;
        this.connecting = false;

        // 保存IP到本地存储
        uni.setStorageSync("robot_ip", this.ip);

        // 设置视频流URL
        const streamUrl = `http://${this.ip}:8000/stream.mjpg`;
        this.videoUrlForWebView = `/static/video.html?url=${encodeURIComponent(streamUrl)}`;

        // 开始轮询状态
        this.fetchStatus();
        this.statusInterval = setInterval(this.fetchStatus, 2000);
      });

      // 收到消息回调
      this.socketTask.onMessage((res) => {
        try {
          const data = JSON.parse(res.data);
          console.log("收到消息:", data);
          
          if (data.action === "get_status" && data.status === "success") {
            // 更新机器人状态
            this.robotStatus = data.data;
            
            // 更新电池电量
            if (data.data.battery !== undefined) {
              this.batteryLevel = Math.max(0, Math.min(100, data.data.battery));
            }
          }
        } catch (e) {
          console.error("解析消息失败:", e);
        }
      });

      // 连接关闭回调
      this.socketTask.onClose(() => {
        this.showToast("warning", "连接断开");
        this.disconnect();
      });

      // 连接错误回调
      this.socketTask.onError((err) => {
        uni.hideLoading();
        this.connecting = false;
        this.connectionError = "连接错误: " + (err.errMsg || "未知错误");
        this.showToast("error", this.connectionError);
        this.disconnect();
      });
      
      // 连接超时处理
      setTimeout(() => {
        if (this.connecting) {
          this.connecting = false;
          this.connectionError = "连接超时";
          this.showToast("error", this.connectionError);
          this.disconnect();
        }
      }, 10000);
    },
    
    // 断开连接
    disconnect() {
      if (this.socketTask) {
        this.socketTask.close();
        this.socketTask = null;
      }
      this.isConnected = false;
      this.connecting = false;
      this.videoUrlForWebView = "";
      
      // 清除定时器
      if (this.statusInterval) {
        clearInterval(this.statusInterval);
        this.statusInterval = null;
      }
      if (this.moveInterval) {
        clearInterval(this.moveInterval);
        this.moveInterval = null;
      }
    },
    
    // 发送控制命令
    sendCommand(action) {
      if (!this.isConnected || !this.socketTask) {
        this.showToast("warning", "请先连接机器人");
        return;
      }
      
      console.log("发送命令:", action);
      this.socketTask.send({
        data: JSON.stringify({ action }),
        success: () => {
          console.log("命令发送成功:", action);
        },
        fail: (err) => {
          console.error("发送指令失败:", err);
          this.showToast("error", "发送指令失败");
        },
      });
    },
    
    // 处理移动开始
    handleMoveStart(direction) {
      if (this.moveInterval) {
        clearInterval(this.moveInterval);
      }
      
      this.currentDirection = direction;
      this.sendCommand(direction);
      
      // 持续发送移动命令
      this.moveInterval = setInterval(() => {
        if (this.isConnected && this.currentDirection === direction) {
          this.sendCommand(direction);
        }
      }, 300);
    },
    
    // 处理移动停止
    handleMoveStop() {
      if (this.moveInterval) {
        clearInterval(this.moveInterval);
        this.moveInterval = null;
      }
      this.currentDirection = "";
      this.sendCommand("stop");
    },
    
    // 获取机器人状态
    fetchStatus() {
      this.sendCommand("get_status");
    },
    
    // 处理视频消息
    handleVideoMessage(e) {
      console.log("收到视频消息:", e.detail.data);
      // 可以在这里处理来自视频页面的消息
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  min-height: 100vh;
}

/* 连接控制栏样式 */
.connection-bar {
  display: flex;
  width: 100%;
  margin-bottom: 10rpx;
  align-items: center;
}

.ip-input {
  flex-grow: 1;
  border: 1px solid #ccc;
  border-radius: 10rpx;
  padding: 15rpx 20rpx;
  margin-right: 20rpx;
  font-size: 28rpx;
  height: 80rpx;
  box-sizing: border-box;
}

.connect-btn {
  flex-shrink: 0;
  width: 160rpx;
  height: 80rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 状态指示器样式 */
.status-indicator {
  width: 100%;
  text-align: center;
  margin-bottom: 20rpx;
  font-size: 28rpx;
  color: #666;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.error-text {
  color: #f44336;
  font-size: 24rpx;
  margin-top: 10rpx;
}

/* 视频容器样式 */
.video-container {
  width: 100%;
  height: 480rpx;
  background-color: #000;
  margin-bottom: 30rpx;
  border-radius: 15rpx;
  overflow: hidden;
  position: relative;
}

.video-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #fff;
  background-color: #333;
}

.placeholder-image {
  width: 150rpx;
  height: 150rpx;
  opacity: 0.7;
  margin-bottom: 20rpx;
}

.placeholder-text {
  font-size: 28rpx;
  color: #aaa;
}

/* 控制面板样式 */
.control-panels {
  display: flex;
  justify-content: space-around;
  width: 100%;
  margin-bottom: 30rpx;
  flex-wrap: wrap;
}

.panel {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30rpx;
  width: 45%;
}

.panel-title {
  font-size: 30rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
}

.d-pad {
  position: relative;
  width: 250rpx;
  height: 250rpx;
  background-color: #f5f5f5;
  border-radius: 20rpx;
}

.d-pad-btn {
  position: absolute;
  width: 80rpx;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 40rpx;
  border-radius: 15rpx;
  background-color: #f0f0f0;
  color: #333;
  border: none;
  padding: 0;
  
  &:active {
    background-color: #e0e0e0;
  }
  
  &[disabled] {
    opacity: 0.5;
    background-color: #e0e0e0;
  }
}

.d-pad-btn.up {
  top: 10rpx;
  left: 50%;
  transform: translateX(-50%);
}

.d-pad-btn.down {
  bottom: 10rpx;
  left: 50%;
  transform: translateX(-50%);
}

.d-pad-btn.left {
  left: 10rpx;
  top: 50%;
  transform: translateY(-50%);
}

.d-pad-btn.right {
  right: 10rpx;
  top: 50%;
  transform: translateY(-50%);
}

.d-pad-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.stop-btn {
  width: 100rpx;
  height: 100rpx;
  font-size: 28rpx;
  border-radius: 50%;
  background-color: #e57373;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
  border: none;
  
  &:active {
    background-color: #d32f2f;
  }
  
  &[disabled] {
    opacity: 0.5;
    background-color: #bdbdbd;
  }
}

.center-btn {
  width: 100rpx;
  height: 100rpx;
  font-size: 28rpx;
  border-radius: 50%;
  background-color: #81c784;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
  border: none;
  
  &:active {
    background-color: #388e3c;
  }
  
  &[disabled] {
    opacity: 0.5;
    background-color: #bdbdbd;
  }
}

/* 功能按钮样式 */
.function-buttons {
  display: flex;
  justify-content: space-around;
  width: 100%;
  margin-bottom: 30rpx;
  flex-wrap: wrap;
}

.function-buttons button {
  margin: 10rpx;
  flex-grow: 1;
  font-size: 28rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &[disabled] {
    opacity: 0.5;
  }
}

/* 状态框样式 */
.status-box {
  width: 100%;
  padding: 20rpx;
  border: 1px solid #eee;
  border-radius: 15rpx;
  background-color: #fafafa;
  margin-bottom: 30rpx;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 0;
  font-size: 28rpx;
  border-bottom: 1px solid #eee;
  
  &:last-child {
    border-bottom: none;
  }
}

.status-value {
  font-weight: bold;
  margin-left: 20rpx;
  text-align: right;
  flex-grow: 1;
}

.status-value.active {
  color: #4caf50;
}

.status-value.danger {
  color: #f44336;
  animation: blink 1s linear infinite;
}

progress {
  width: 100rpx;
  margin-left: 20rpx;
}

@keyframes blink {
  50% {
    opacity: 0.5;
  }
}

/* 暗黑模式样式 */
.dark {
  background-color: #121212;
  
  .panel-title {
    color: #e0e0e0;
  }
  
  .status-box {
    background-color: #1e1e1e;
    border-color: #333;
  }
  
  .status-item {
    color: #ccc;
    border-bottom: 1px solid #333;
  }
  
  .status-value {
    color: #fff;
  }
  
  .status-value.active {
    color: #80e27e;
  }
  
  .status-value.danger {
    color: #ff5252;
  }
  
  .video-container {
    background-color: #000;
  }
  
  .video-placeholder {
    background-color: #1a1a1a;
  }
  
  .placeholder-text {
    color: #999;
  }
  
  .d-pad {
    background-color: #2a2a2a;
  }
  
  .d-pad-btn {
    background-color: #333;
    color: #fff;
    
    &:active {
      background-color: #444;
    }
    
    &[disabled] {
      background-color: #222;
    }
  }
  
  .stop-btn {
    background-color: #d32f2f;
    
    &:active {
      background-color: #b71c1c;
    }
    
    &[disabled] {
      background-color: #333;
    }
  }
  
  .center-btn {
    background-color: #388e3c;
    
    &:active {
      background-color: #2e7d32;
    }
    
    &[disabled] {
      background-color: #333;
    }
  }
  
  .ip-input {
    background-color: #1e1e1e;
    color: #fff;
    border: 1px solid #555;
  }
  
  .status-indicator {
    color: #aaa;
  }
  
  progress {
    background-color: #333;
  }
}
</style>